import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:sptapp/moudle/event_bus.dart';
import 'package:sptapp/moudle/message.dart';
import 'package:sptapp/page/home/home.dart';
import 'package:sptapp/page/home/home_new.dart';
import 'package:sptapp/page/min/min_new_page.dart';
import 'package:sptapp/page/monitor/inverter_detail.dart';
import 'package:sptapp/page/monitor/monitor.dart';

import '../config/const.dart';
import '../moudle/common_info.dart';
import 'monitor/monitor_statistical.dart';

int homeSelType = -1;
class IndexPage extends StatefulWidget {
  const IndexPage({super.key});

  @override
  State<IndexPage> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> with SingleTickerProviderStateMixin,WidgetsBindingObserver,AutomaticKeepAliveClientMixin{

  late TabController tabController;
  int tabIndex = 0;
  late StreamSubscription _subscription;

  List<Widget> tabContents = [
    HomePage(),
    // HomeNewPage(),
    MonitorStatisticalPage(),
    InverterDetailPage(),
    MinNewPage()
  ];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    tabController = TabController(length: 4, vsync: this);
    WidgetsBinding.instance.addObserver(this);
    tabController.addListener(_tabListener);
    _subscription = eventBus.on<HomeDataClick>().listen((val){
      homeSelType = val.index;
      tabClick(1);
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
    tabController.removeListener(_tabListener);
    _subscription.cancel();
  }
  void tabClick(int index){
    setState(() {
      tabIndex=index;
      tabController.animateTo(tabIndex,);
    });
  }
  void _tabListener(){
    setState(() {
      tabIndex=tabController.index;
    });
    eventBus.fire(DeviceInfoChange());
    print('当前indexing   $tabIndex');
  }

  Widget _tabIcon(int index, String name,String imgUrl, String selImgUrl){
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Image.asset(tabIndex==index?selImgUrl:imgUrl,width: 48.w,height: 48.w,),
          SizedBox(height: 6.w,),
          Text(name,style: TextStyle(
              color: tabIndex==index?whiteFontColor:Color.fromRGBO(255, 255, 255, 0.5),
              fontSize: 24.sp,
              fontWeight: tabIndex==index? FontWeight.w400:FontWeight.w400
          ),),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      body: Container(
        child: Column(
          children: [
            // _topWidget(),
            Expanded(child: TabBarView(
              // physics: NeverScrollableScrollPhysics(),
              controller: tabController,
              children: tabContents,
            )),
          ],
        ),
      ),
      bottomNavigationBar: Container(
        padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight>0?20.w:0,top: 10.w),
        height: 120.w+(ScreenUtil().bottomBarHeight>0?20.w:0),
        decoration: BoxDecoration(
            color: Colors.black,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 10,
              ),
            ]
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            GestureDetector(
              onTap: (){
                if(tabIndex!=0){
                  tabClick(0);
                }
              },
              child: Container(
                width: 1.sw/4,
                alignment: Alignment.center,
                color: Colors.transparent,
                child: _tabIcon(0,tab_index_home.tr, 'assets/tab/home.png', 'assets/tab/home_sel.png'),
              ),
            ),
            GestureDetector(
              onTap: (){
                if(tabIndex!=1){
                  tabClick(1);
                }
              },
              child: Container(
                width: 1.sw/4,
                alignment: Alignment.center,
                color: Colors.transparent,
                child: _tabIcon(1, tab_index_monitor.tr,'assets/tab/monitior.png', 'assets/tab/monitior_sel.png'),
              ),
            ),
            GestureDetector(
              onTap: (){
                if(tabIndex!=2){
                  tabClick(2);
                }
              },
              child: Container(
                width: 1.sw/4,
                alignment: Alignment.center,
                color: Colors.transparent,
                child: _tabIcon(2, tab_index_device.tr,'assets/tab/device.png', 'assets/tab/device_sel.png'),
              ),
            ),
            GestureDetector(
              onTap: (){
                if(tabIndex!=3){
                  tabClick(3);
                }
              },
              child: Container(
                width: 1.sw/4,
                alignment: Alignment.center,
                color: Colors.transparent,
                child: _tabIcon(3, 'Me'.tr,'assets/tab/min.png', 'assets/tab/min_sel.png'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _topWidget(){
    return Container(
      child: Column(
        children: [
          SizedBox(height: ScreenUtil().statusBarHeight+10.w,),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 30.w),
            height: 44,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: (){
                    SmartDialog.show(builder: (ctx){
                      return Container(
                        decoration: BoxDecoration(
                            color: Color(0xff1E1D20)
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(height: ScreenUtil().statusBarHeight+10.w,),
                            Container(
                              padding: EdgeInsets.symmetric(horizontal: 30.w),
                              height: 44,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  GestureDetector(
                                    onTap: (){
                                      SmartDialog.dismiss();
                                    },
                                    child: Row(
                                      children: [
                                        Container(
                                          constraints: BoxConstraints(
                                              maxWidth: 350.w
                                          ),
                                          child: Text(baseUserInfo['nickname']??'',style: TextStyle(
                                              color: whiteFontColor,
                                              fontSize: 36.sp,
                                              height: 1.6,
                                              fontWeight: FontWeight.w600
                                          ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                                        ),
                                        SizedBox(width: 2.w,),
                                        Image.asset('assets/common/control_down.png',width: 40.w,)
                                      ],
                                    ),
                                  ),
                                  Container(
                                    child: Text('Discharging',style: TextStyle(
                                        color:Color(0xff06df85),
                                        fontSize: 28.sp,
                                        fontWeight: FontWeight.w600
                                    ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      );
                    },alignment: Alignment.topCenter,animationTime: Duration.zero);
                  },
                  child: Row(
                    children: [
                      Container(
                        constraints: BoxConstraints(
                            maxWidth: 350.w
                        ),
                        child: Text(baseUserInfo['nickname']??'',style: TextStyle(
                            color: whiteFontColor,
                            fontSize: 36.sp,
                            height: 1.6,
                            fontWeight: FontWeight.w600
                        ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                      ),
                      SizedBox(width: 2.w,),
                      Image.asset('assets/common/control_down.png',width: 40.w,)
                    ],
                  ),
                ),
                Container(
                  child: Text('Discharging',style: TextStyle(
                      color:Color(0xff06df85),
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w600
                  ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    eventBus.fire(DeviceInfoChange());
    print('发送重新请求====');
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

}
